import type { VercelRequest, VercelResponse } from "@vercel/node";
import { FeiShuTable, getTableRecords, saveTableRecords } from "../feishu/bitable";

export default async function handler(req: VercelRequest, res: VercelResponse) {

    if (req.method == "GET") {
        let urlParam = '';

        const data = await getTableRecords(FeiShuTable.User, urlParam)

        return res.status(200).json({
            message: 'query success',
            data
        });
    }

    if (req.method == "POST") {
        const body = req.body;

        for (const key in body) {
            if (!body[key]) {
                return res.status(400).json(
                    { messsage: UserFieldsMessage[key] }
                ).end();
            }
        }

        const { password, confirmPassword, ...record } = body;

        if (password !== confirmPassword) {
            return res.status(400).json({ messsage: 'passwords does not match!' }).end();
        }

        const data = await saveTableRecords(FeiShuTable.User, { password, ...record })

        return res.status(201).json({
            message: 'created success',
            data
        });
    }

    return res.status(200).json({
        message: 'executed success',
    });
}

enum UserFields {
    username = "username",
    password = "password",
    confirmPassword = "confirmPassword",
}

const UserFieldsMessage = {
    [UserFields.username]: 'username is empty',
    [UserFields.password]: 'password is empty',
    [UserFields.confirmPassword]: 'confirmPassword is empty',
};